package com.xuxu.blog.controller.alipay;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.xuxu.blog.dao.TOrdersDao;
import com.xuxu.blog.dao.UserDao;
import com.xuxu.blog.entity.bean.AliPayEntity;
import com.xuxu.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: AliPayController
 * @author: Maxuxu
 * @date: 2022/8/28 21:56
 * @description: 阿里支付的控制类
 */
@RestController
@RequestMapping("/blog/alipay")
@Api(value = "AliPayController", tags = "支付宝接口")
@Slf4j
public class AliPayController {
    @Resource
    private TOrdersDao tOrdersDao;

    @Resource
    private HttpServletRequest request;

    @Resource
    private UserDao userDao;

    @GetMapping("/pay")
    @ApiOperation("支付接口")
    public String pay(AliPayEntity aliPay) {
        log.error("alipay获取到的数据是：{}",aliPay);
        AlipayTradePagePayResponse response;
        try {
            //  发起API调用（以创建当面付收款二维码为例）
            response = Factory.Payment.Page()
                    .pay(aliPay.getSubject() + " 积分", aliPay.getTraceNo(),
                            aliPay.getTotalAmount(),
                            "http://192.168.123.223:884/api/blog/alipay/notify");
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return response.getBody();
    }
    @ApiOperation("回调函数")
    @GetMapping("/notify")  // 注意这里必须是POST接口
    public R payNotify(HttpServletRequest request) throws Exception {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            log.debug("获取到的对象数据是:{}", params);
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                String traceNo = params.get("out_trade_no");
                // 更新订单为已支付
                tOrdersDao.updateState(traceNo, 1,params.get("timestamp"));
                Integer uid = TOrdersController.Uid;
                String subject = params.get("total_amount");
                int index = subject.indexOf(".");
                String substring = subject.substring(0, index);
                int sumPoints = Integer.parseInt(substring)*10;
                // 更新用户信息，增加积分
                userDao.updatePoint(sumPoints, uid);
            }
                return R.ok("付款成功");
    }
}
